import pyecharts as pye
from pyecharts.globals import ThemeType
f = open("./1960-2019全球GDP数据.csv","r",encoding="GB2312")
data_lines = f.readlines()
f.close()
data_lines.pop(0)
data_dict={}
for line in data_lines:
    year = int(line.split(",")[0])  # 年份
    country = line.split(",")[1]    # 国家
    gdp = float(line.split(",")[2]) # 生产总值
    try:    # 如果字典里有这个年份，那直接添加国家和GDP信息
        data_dict[year].append([country,gdp])
    except KeyError:    # 如果字典里没有这个年份，那先定义一下这个年份，然后在加信息
        data_dict[year] = []
        data_dict[year].append([country,gdp])
sorted_year = sorted(data_dict.keys())
#print(sorted_year)
timeline = pye.charts.Timeline({"theme":ThemeType.LIGHT})
#print(data_dict[1960])
for year in sorted_year:
    #data_dict[year].sort(key=lambda element: element[1],reversed=True)
    data_dict[year].sort(key=lambda element: element[1], reverse=1)
    year_data = data_dict[year][0:8]
    x_data = []
    y_data = []
    for country_gdp in year_data:
        bar = pye.charts.Bar()
        x_data.append(country_gdp[0])
        y_data.append(country_gdp[1] / 100000000)
        bar.add_xaxis(x_data[::-1])
        bar.add_yaxis("GDP(亿)",
                      y_data[::-1],
                      label_opts=pye.options.LabelOpts(position="right"))
        bar.reversal_axis()
        bar.set_global_opts(
            title_opts=pye.options.TitleOpts(title=f"{year}年全球GDP排名前8",pos_top="5%",pos_right="center")
        )
    timeline.add(bar,year)
timeline.add_schema(
    play_interval=400,# 播放速度
    is_loop_play=False# 循环播放
)
timeline.render("动态柱状图.html")